import random

from django.shortcuts import render
from rest_framework.views import APIView
from django_redis import get_redis_connection
from django.http import HttpResponse
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response
from rest_framework import status
import logging

from meiduo_mall.libs.captcha.captcha import captcha
from . import constants
from .serializers import ImageCodeCheckSerializer
from meiduo_mall.utils.yuntongxun.sms import CCP
from celery_tasks.sms.tasks import send_sms_code
# Create your views here.

logger = logging.getLogger('django')


class ImageCodeView(APIView):
    """
    图片验证码
    GET /image_codes/(?P<image_code_id>[\w-]+)/
    """
    def get(self, request, image_code_id):
        # 生成图片验证码
        text, image = captcha.generate_captcha()

        # 保存图片验证码内容
        # 通过调用get_redis_connection方法传递redis的配置名称可获取到redis的连接对象
        redis_conn = get_redis_connection('verify_codes')
        # 通过redis连接对象可以执行redis命令
        redis_conn.setex('img_%s' % image_code_id, constants.IMAGE_CODE_REDIS_EXPIRES, text)

        # 返回响应
        return HttpResponse(image, content_type='image/jpg')


class SMSCodeView(GenericAPIView):
    """
    短信验证码
     GET /sms_codes/(?P<mobile>1[3-9]\d{9})/?image_code_id=xxx&text=xxx
    """
    serializer_class = ImageCodeCheckSerializer

    def get(self, request, mobile):
        # 校验参数，使用序列化器完成
        serializer = self.get_serializer(data=request.query_params)
        serializer.is_valid(raise_exception=True)

        # 生成短信验证码
        sms_code = "%06d" % random.randint(0, 999999)

        # 保存短信验证码内容，保存发送记录
        redis_conn = get_redis_connection('verify_codes')
        # redis_conn.setex('sms_%s' % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        # redis_conn.setex('send_flag_%s' % mobile, constants.SEND_SMS_CODE_INTERVAL, 1)

        # redis管道
        pl = redis_conn.pipeline()
        pl.setex('sms_%s' % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        pl.setex('send_flag_%s' % mobile, constants.SEND_SMS_CODE_INTERVAL, 1)

        # 让管道通知redis执行命令
        pl.execute()

        # print(sms_code)

        # 发送短信
        # try:
        #     ccp = CCP()
        #     result = ccp.send_template_sms(mobile, [sms_code, constants.SMS_CODE_REDIS_EXPIRES // 60], constants.SMS_CODE_TEMP_ID)
        # except Exception as e:
        #     logger.error("发送短信验证码[异常][mobile: %s, message: %s]" % (mobile, e))
        #     return Response({'message': 'failed'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        # else:
        #     if result == 0:
        #         # 发送成功
        #         logger.info("发送短信验证码成功[mobile: %s]" % mobile)
        #         return Response({'message': 'OK'})
        #     else:
        #         # 发送失败
        #         logger.warning("发送短信验证码失败[mobile: %s]" % mobile)
        #         return Response({'message': 'failed'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

        # 使用celery异步发送短信验证码
        send_sms_code.delay(mobile, sms_code, constants.SMS_CODE_REDIS_EXPIRES // 60, constants.SMS_CODE_TEMP_ID)

        return Response({'message': 'OK'})